package com.pinecone.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.pinecone.common.Constant.RoleConstant;
import com.pinecone.common.annotation.CurrentUser;
import com.pinecone.common.exception.MinerException;
import com.pinecone.common.utils.CvsUtil;
import com.pinecone.common.validator.group.UpdateGroup;
import com.pinecone.dto.HostAndPrincipalDTO;
import com.pinecone.dto.UserDetailsDTO;
import com.pinecone.service.CusPrincipalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.pinecone.entity.CusHostEntity;
import com.pinecone.service.CusHostService;
import com.pinecone.common.utils.PageUtils;
import com.pinecone.common.utils.Query;
import com.pinecone.common.utils.R;

import javax.servlet.http.HttpServletResponse;


/**
 * 主播信息表
 *
 * @author hushangjie
 * @email 979783618@qq.com
 * @date 2017-09-27 21:17:58
 */
@RestController
@RequestMapping("cus_host")
public class CusHostController extends BaseController{


    @Autowired
    private CusHostService cusHostService;
    @Autowired
    private CusPrincipalService cusPrincipalService;

    /**
     * 机构管理员创建小主播
     *
     * @param currentUser
     * @param hostEntity
     * @return
     */
    @PreAuthorize("hasRole('ROLE_ORGMASTER')")
    @PostMapping("/add")
    public R addHost(@CurrentUser UserDetailsDTO currentUser, @RequestBody @Validated CusHostEntity hostEntity) {
        //确保前端传来的信息无误
        hostEntity.setCreateTime(null)
                .setCustomerId(null)
                .setHostId(null)
                .setOrgId(currentUser.getOrgId());
        //添加主播
        cusHostService.addHost(hostEntity, currentUser.getId());
        return R.ok();
    }

    /**
     * 获取所有主播列表，机构管理员只能获取本机构下的主播
     *
     * @param params
     * @return
     */
    @PreAuthorize("hasAnyRole('ROLE_ORGMASTER','ROLE_SYSADMIN')")
    @GetMapping("")
    public R list(@RequestParam Map<String, Object> params, @CurrentUser UserDetailsDTO currentUser) {
        if (currentUser.getRolename().equals(RoleConstant.ORGMASTER)) {
            //机构管理员只能获取本机构内部成员
            if (params.get("orgId") == null && params.get("orgId")!= "") {
                throw new MinerException("无权操作", 400);
            }
            params.put("orgId", currentUser.getOrgId());
        }
        //查询列表数据
        Query query = new Query(params);
        if (params.get("page") != null && params.get("limit") != null) {
            List<HostAndPrincipalDTO> cusHostList = cusHostService.queryCombineList(query);
            int total = cusHostService.queryCombineTotal(query);

            PageUtils pageUtil = new PageUtils(cusHostList, total, query.getLimit(), query.getPage());

            return R.ok().put("page", pageUtil);
        } else {
            List<HostAndPrincipalDTO> cusHostList = cusHostService.queryCombineList(query);
            return R.ok().put("list", cusHostList);
        }

    }


    /**
     * 查询单个主播信息
     *
     * @param hostId
     * @return
     */
    @GetMapping("/{hostId}")
    public R info(@PathVariable("hostId") Long hostId) {
        CusHostEntity cusHost = cusHostService.queryObject(hostId);

        return R.ok().put("cusHost", cusHost);
    }

    //根据直播间获取主播信息
    @GetMapping("/live_room/{live_room_id}")
    public R getHostByLiveRoomId(@PathVariable(value = "live_room_id",required = true) String liveRoomId){
        CusHostEntity cusHostEntity = cusHostService.queryByLiveRoomId(liveRoomId);
        return R.ok().put("cusHost", cusHostEntity);
    }
    /**
     * 保存
     */
    /*@PostMapping("")
	public R save(@RequestBody CusHostEntity cusHost){
		cusHostService.save(cusHost);
		
		return R.ok();
	}*/

    /**
     * 更新主播信息
     *
     * @param currentUser
     * @param cusHost
     * @return
     */
    @PutMapping("")
    public R update(@CurrentUser UserDetailsDTO currentUser, @RequestBody @Validated({UpdateGroup.class}) CusHostEntity cusHost) {
        if (currentUser.getRolename().equals(RoleConstant.ORGHOST)) {
            //主播只能更新自己的信息
            if (currentUser.getId() != cusHost.getCustomerId()) {
                throw new MinerException("无权操作");
            }
        }
        if (currentUser.getRolename().equals(RoleConstant.ORGMASTER)) {
            //机构管理员只能操作本机构成员
            CusHostEntity hostEntity = cusHostService.queryObject(cusHost.getHostId());
            if (hostEntity.getOrgId() != currentUser.getOrgId()) {
                throw new MinerException("无权操作");
            }
        }

        cusHostService.update(cusHost);

        return R.ok();
    }


    /**
     * 删除某个主播
     *
     * @param currentUser
     * @param hostId
     * @return
     */
    @PreAuthorize("hasAnyRole('ROLE_SYSADMIN','ROLE_ORGMASTER')")
    @DeleteMapping("/{host_id}")
    public R forbidHost(@CurrentUser UserDetailsDTO currentUser, @PathVariable(value = "host_id", required = true) Long hostId) {
        CusHostEntity hostEntity = cusHostService.queryObject(hostId);
        if (hostEntity == null) {
            throw new MinerException("该主播不存在");
        }
        if (currentUser.getRolename().equals(RoleConstant.ORGMASTER)) {
            //机构管理员只能禁用本机构的主播
            if (hostEntity.getOrgId() != currentUser.getOrgId()) {
                throw new MinerException("无权操作", 403);
            }
        }
        //删除主播信息表
        cusHostService.delete(hostId);
        //删除主播账号表
        cusPrincipalService.delete(hostEntity.getCustomerId());
        return R.ok();
    }

    //导出某个机构所有主播信息cvs
    /*@PreAuthorize("hasAnyRole('ROLE_SYSADMIN','ROLE_ORGMASTER')")*/
    @GetMapping("/export_cvs/{orgId}")
    public R exportCvs(@CurrentUser UserDetailsDTO currentUser, @PathVariable(value = "orgId", required = true) Integer orgId,
                       HttpServletResponse response) {
        /*if (currentUser.getRolename().equals(RoleConstant.ORGMASTER)) {
            if (currentUser.getOrgId() != orgId) {
                throw new MinerException("无权操作", 403);
            }
        }*/
        List<HostAndPrincipalDTO> cusHostLists = cusHostService.queryCombineListByOrgId(orgId);

        String sTitle = "主播名称,部门,登录账号,手机号,qq号,邮箱,备注";
        String fName = "主播名单_";
        String mapKey = "hostName,department,cusAccount,hostPhone,hostQq,hostEmail,remark";
        List<Map<String, Object>> dataList = new ArrayList<>();
        Map<String, Object> map = null;
        for (HostAndPrincipalDTO host : cusHostLists) {
            map = new HashMap<String, Object>();
            map.put("hostName", host.getHostName());
            map.put("department", host.getDepartment());
            map.put("cusAccount", host.getCusAccount());
            map.put("hostPhone", host.getHostPhone());
            map.put("hostQq", host.getHostQq());
            map.put("hostEmail", host.getHostEmail());
            map.put("remark", host.getRemark());
            dataList.add(map);
        }
        try (final OutputStream os = response.getOutputStream()) {
            CvsUtil.responseSetProperties(fName, response);
            CvsUtil.doExport(dataList, sTitle, mapKey, os);
            return R.ok();

        } catch (Exception e) {
            logger.error("导出CSV失败", e);

        }
        return R.error("导出出错！");
    }

}
